package net.oschina.android.ui.activity;

import net.oschina.android.R;
import net.oschina.android.app.AppContext;
import net.oschina.android.app.AppException;
import net.oschina.android.app.AppUtil;
import net.oschina.android.app.BroadcastController;
import net.oschina.android.app.Contanst;
import net.oschina.android.model.User;
import net.oschina.android.util.CyptoUtils;
import net.oschina.android.util.UIHelper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * @author HuangWenwei
 *
 * @date 2014年9月3日
 */
public class loginActivity extends Activity implements OnClickListener,OnEditorActionListener{
	
	private TextWatcher textWatcher;
	private EditText mAcount;
	private EditText mPassword;
	private CheckBox chb_rememberMe;
	private Button btLogin;
	private AppContext mContext;
	private ProgressDialog mLoginProgressDialog;
	boolean isRemenberUserInfo=false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		mContext = (AppContext) getApplication();
		initView();
	}

	/**
	 *2014年9月3日
	 */
	private void initView() {
		mAcount =  (EditText) findViewById(R.id.login_account_edittext);
		mPassword = (EditText) findViewById(R.id.login_passwd_edittext);
		chb_rememberMe = (CheckBox) findViewById(R.id.login_remember_checkbox);
		isRemenberUserInfo = chb_rememberMe.isChecked();
		btLogin = (Button) findViewById(R.id.login_button);
		btLogin.setOnClickListener(this);
		
		textWatcher = new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				String acount = mAcount.getText().toString();
				String password = mPassword.getText().toString();
				if(TextUtils.isEmpty(acount)||TextUtils.isEmpty(password))
					btLogin.setEnabled(false);
				else
					btLogin.setEnabled(true);
			}
		};
		mAcount.addTextChangedListener(textWatcher);
		mPassword.addTextChangedListener(textWatcher);
		mPassword.setOnEditorActionListener(this);
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		String username = sp.getString("username", "");
		String password = sp.getString("password", "");
		if(null!=username && null!=password){
			String account = CyptoUtils.decode(Contanst.ACCOUNT_EMAIL, username);
			mAcount.setText(account);
			String pwd = CyptoUtils.decode(Contanst.ACCOUNT_PWD, password);
			mPassword.setText(pwd);	
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if(actionId == EditorInfo.IME_ACTION_DONE){
			checkLogin();
			AppUtil.hideInputMethod(mPassword,this);
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		AppUtil.hideInputMethod(mPassword,this);
		checkLogin();
	}

	/**
	 * 检查登录
	 *2014年9月4日
	 */
	private void checkLogin() {
		
		String email = mAcount.getText().toString();
		String password = mPassword.getText().toString();
		
		//检查用户输入的参数
		if(TextUtils.isEmpty(email)){
			UIHelper.ToastMessage(this, getString(R.string.msg_login_email_null));
			return;
		}

		if(TextUtils.isEmpty(password)){
			UIHelper.ToastMessage(this, getString(R.string.msg_login_pwd_null));
			return;
		}
		
		mContext.saveAccountInfo(CyptoUtils.encode(Contanst.ACCOUNT_EMAIL, email),
				CyptoUtils.encode(Contanst.ACCOUNT_PWD, password));
		login(email,password);
	}

	/**
	 *2014年9月4日
	 *@param email
	 *@param password
	 */
	private void login(final String email, final String password) {
		
		if(mLoginProgressDialog == null){
			mLoginProgressDialog = new ProgressDialog(this);
			mLoginProgressDialog.setCancelable(true);
			mLoginProgressDialog.setCanceledOnTouchOutside(false);
			mLoginProgressDialog.setMessage(getString(R.string.login));
		}
		
		new AsyncTask<Void, Void, Message>(){
			
			@Override
			protected Message doInBackground(Void... params) {
				Message msg = new Message();
				try {
					User user =mContext.loginVerify(email, password, isRemenberUserInfo);
					msg.what = 1;
					msg.obj = user;
				} catch (AppException e) {
					msg.what = -1;
					msg.obj = e;
					if(mLoginProgressDialog!=null){
						mLoginProgressDialog.dismiss();
					}
				}
				return msg;
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if(mLoginProgressDialog!=null)
					mLoginProgressDialog.dismiss();
			}

			@Override
			protected void onPostExecute(Message result) {
				super.onPostExecute(result);
				if(isFinishing())
					return;
				if(mLoginProgressDialog!=null)
					mLoginProgressDialog.dismiss();
				Context context = loginActivity.this;
				if(result.what ==1){
					User user = (User) result.obj;
					if(null!=user)
						UIHelper.ToastMessage(context, "登录成功");
					setResult(RESULT_OK);
					BroadcastController.sendUserChangeBroadcase(context);
					finish();
				}else if(result.what ==0)
					UIHelper.ToastMessage(context, "登录失败"+result.obj);
				else if(result.what == -1){
					if(result.obj instanceof AppException){
						AppException e = (AppException) result.obj;
						if(e.getCode() == 401)
							UIHelper.ToastMessage(context, "登录错误");
						else 
							((AppException)result.obj).makeToast(context);
					}else{
						UIHelper.ToastMessage(context, "登录错误");
					}
				}
			}
			
		}.execute();
	}
}